<?php
/**
 * Description of UserController
 *
 * @author TheFaSTeR
 */

Yii::import( "ext.xupload.models.XUploadForm" );
Yii::import( "ext.xupload.models.ImageUploadForm" );
Yii::import("application.controllers.FrontendBaseController");

class UserController extends FrontendBaseController
{  
    public function actionIndex( $id )
    {
        $user = $this->loadModel($id);        
        $pets = null;
        $isAuthor = false; 
        $petsCount = null;
        if (!Yii::app()->user->isGuest && $id == Yii::app()->user->id)
        {
            $isAuthor = true;
            $user = $this->loadModel(Yii::app()->user->id);
            $this->breadcrumbs = array( "Главная" => "/",
                                "$user->name $user->surname" => '');
        }
        else
        {
            $this->breadcrumbs = array( "Главная" => "/",
                                "Пользователи" => "/user/all",
                                "$user->name $user->surname" => '');
        }
        
        $friendsList = FriendFacade::getLatestFriendsByUser($user->user_id);   
        $friendsCount = FriendFacade::getFriendsCountByUserId($user->user_id);

        $pets = PetFacade::getPetsByUserId($user->user_id);
        $petsCount = PetFacade::getPetsCountByUserId($user->user_id);    
        
        $idFriend = false;
        if ($user->user_id != Yii::app()->user->id)
        {
            $isFriend = FriendFacade::getFriendId(Yii::app()->user->id, $user->user_id);            
        }        
        
        if ($isAuthor)
        {
            $waitFriendsCount = FriendFacade::getWaitFriendsCount($user->user_id);
        }
        
        $posts = PostFacade::getLatestPostsByUser($user->user_id);
        $postsCount = PostFacade::getPostsCountByUser($user->user_id);
        
        $albums = PhotoFacade::getUserPhotoAlbums($user->user_id);
        $albumsCount = PhotoFacade::getCountPhotoAlbumsByUser($user->user_id);
        
        $this->render('user', array(
            'user'              => $user, 
            'isAuthor'          => $isAuthor, 
            'pets'              => $pets, 
            'petsCount'         => $petsCount,
            'friends'           => $friendsList,
            'friendsCount'      => $friendsCount,
            'isFriend'          => $isFriend,
            'waitFriendsCount'  => $waitFriendsCount,
            'posts'             => $posts,
            'postsCount'        => $postsCount,
            'albums'            => $albums,
            'albumsCount'       => $albumsCount
            )
        );
    }

    public function actionRegister()
    {
        $this->breadcrumbs = array( "Главная" => "/",
                                    "Регистрация" => "");

        if (!Yii::app()->user->isGuest)
        {
            $this->redirectToUserPage();
        }
        $model = new User();
        $status = "";
	if(isset($_POST['User']))
        {            
            $model->attributes=$_POST['User'];            
            if (!is_null(UserFacade::getUserByEmail($model->email)))
            {
                $status = "Такой почтовый ящик уже зарегистрирован";
            }
            else
            {
                if (UserFacade::AddUser($model))
                {
                    $this->redirect("/site/login");
                    $status = $model->name . "! Спасибо за регистрацию!";
                }
            }
        }
        $model->password = "";
        $this->render('register', array(
            "model"     => $model,
            "status"    => $status
        ));
    }
    
    public function actionUpdateAvatar()
    {
        $this->breadcrumbs = array( "Главная" => "/",
                                    "Моя страница" => $this->getUserMainPageUrl(),
                                    "Изменить фотографию" => "" );
        $model = $this->getUserFromSession();
        $this->render('updateAvatar', array("user"=>$model));
    }

    public function actionDeleteAvatar()
    {
        $model = $this->getUserFromSession();
        UserFacade::deleteUserAvatar($model);
        $this->redirect("/user/updateAvatar");
    }

    public function actionUpdate( $id )
    {                
        $model = $this->loadModel($id);
        
        $this->breadcrumbs = array( "Главная" => "/",
                                    "Моя страница" => $this->getUserMainPageUrl(),
                                    "Редактировать страницу" => '');

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if ( isset( $_POST[ 'User' ] ) )
        {
            $model->attributes = $_POST[ 'User' ];
            if ( UserFacade::saveUser( $model ) )   
            {
                $this->redirect($this->redirectToUserPage());
            }                
        }

        $this->render( 'update', array(
            'model' => $model,
        ) );
    }       
    
    public function loadModel( $id )
    {
        $model = UserFacade::getUserById( $id );
        if ( $model === null )
            throw new CHttpException( 404, 'The requested page does not exist.' );
        return $model;
    }

    public function actionAll()
    {
        $model = new User;
        $model->unsetAttributes();  // clear any default values
        $this->registerAjaxSearch("user-search", "user-list");
        $this->breadcrumbs = array( "Главная" => "/",
                                    "Все пользователи" => "" );

        $name = $_GET['User']['name'];
        $surname = $_GET['User']['surname'];
        $city = $_GET['User']['city'];
        $dataProvider = UserFacade::getDataProviderForSearch($name, $surname, $city);

        $this->render( 'all', array(
            'dataProvider' => $dataProvider,
            'searchModel' => $model
        ) );
    }
    
}
?>
